<template>
    <div>
        <el-row>
            <el-col :span="6"><el-input v-model="carname" size="mini" placeholder="请输入车辆名称"></el-input></el-col>
            <el-col :span="6"><el-button type="primary" @click="search"  size="mini" icon="el-icon-search">搜索</el-button>
            &nbsp;<el-button type="primary"  size="mini" icon="el-icon-circle-plus" @click="handleAdd">添加</el-button></el-col>
            <el-col :span="6"><div class="grid-content bg-purple-light">&nbsp;</div></el-col>
        </el-row>
        <el-row>
            <el-table
                    :data="tableData"
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        label="车辆编号"
                        v-if="false">
                </el-table-column>
                <el-table-column
                        prop="carname"
                        label="车辆名称">
                </el-table-column>
                <el-table-column
                        prop="typeName"
                        label="车辆类型">
                </el-table-column>
                <el-table-column
                        prop="brandName"
                        label="车辆品牌名称">
                </el-table-column>
                <el-table-column
                        prop="typename"
                        label="车辆款式">
                </el-table-column>
                <el-table-column
                        prop="vin"
                        label="车辆唯一识别码">
                </el-table-column>
                 <el-table-column
                        prop="stateName"
                        label="车辆当前状态">
                        <template slot-scope="scope">
                        <span v-if="scope.row.state == 1">空闲</span>
                        <span v-if="scope.row.state == 2">维修</span>
                        <span v-if="scope.row.state == 3">出租</span>
                        </template>
                </el-table-column>
                <el-table-column
                        prop="price"
                        label="价格">
                </el-table-column>
                <el-table-column
                        prop="coverImg"
                        label="图片">
                        <template slot-scope="scope">
                            <el-image
                                    style="width: 50px; height: 50px"
                                    :src="scope.row.coverImg"
                                     ></el-image>
                        </template>  
                </el-table-column>
                <el-table-column label="操作" width="250">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button  v-if="scope.row.state==1||scope.row.state==2"
                                size="mini"
                                @click="handleMaintain(scope.$index, scope.row)">{{ scope.row.state | statusbtn() }}</el-button>
                        <el-button  v-if="scope.row.state==1||scope.row.state==2||scope.row.state==3"
                                size="mini"
                                @click="handleInsurance(scope.$index, scope.row)">{{ scope.row.insuranceId | statubtn() }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--新增/修改 Form -->
            <el-dialog title="车辆管理" :visible.sync="dialogFormVisible">
                <el-form :model="form" :rules="rules" ref="form" >
                     
                     <el-form-item label="图片上传" >
                        <!--图片上传-->
                        <el-upload
                                class="avatar-uploader"
                                :action="url"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                   
                    <el-form-item label="车名" :label-width="formLabelWidth" prop="carname">
                        <el-input v-model="form.carname" placeholder="车名" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="车类型" :label-width="formLabelWidth" prop="type">
                        <el-select v-model="form.type" placeholder="请选择">
                            <el-option v-for="item in optionsType" :key="item.id" :label="item.typeName" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="车辆品牌" :label-width="formLabelWidth" prop="brandId">
                        <el-select v-model="form.brandId" placeholder="请选择">
                            <el-option v-for="item in optionsBrand" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="配置" :label-width="formLabelWidth" prop="configId">
                        <el-select v-model="form.configId" placeholder="请选择">
                            <el-option v-for="item in optionsConfig" :key="item.id" :label="item.typename" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="车辆标识码" :label-width="formLabelWidth" prop="vin">
                        <el-input v-model="form.vin" placeholder="车辆标识码" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="车辆进价" :label-width="formLabelWidth" prop="buyPrice">
                        <el-input v-model="form.buyPrice" placeholder="车辆进价" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="车辆租价" :label-width="formLabelWidth" prop="price">
                        <el-input v-model="form.price" placeholder="车辆租价" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="车辆状态" :label-width="formLabelWidth" prop="state">
                        <el-select v-model="form.state" placeholder="请选择">
                            <el-option value="1">空闲</el-option>
                            <el-option value="2">维修</el-option>
                            <el-option value="3">出租</el-option>
                            <!-- <el-option v-for="item in optionsState" :key="item.id" :label="item.stateName" :value="item.id"> </el-option> -->
                        </el-select>
                    </el-form-item>
                    <el-form-item label="门店" :label-width="formLabelWidth" prop="shopId">
                        <el-select v-model="form.shopId" placeholder="请选择">
                            <el-option v-for="item in optionsShop" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="简介" :label-width="formLabelWidth" prop="intro">
                        <el-input v-model="form.intro" placeholder="简介" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveInfo(form)">确 定</el-button>
                </div>
            </el-dialog>
            <!--维修 -->
            <el-dialog title="车辆维修管理" :visible.sync="maintainForm">
                <el-form :model="form" :rules="rules" ref="form">
                    <el-form-item label="车名" :label-width="formLabelWidth">
                        <el-input v-model="form.carname" placeholder="车名" auto-complete="off" readonly="readonly"></el-input>
                    </el-form-item>
                    <el-form-item label="车辆编号" :label-width="formLabelWidth">
                        <el-input v-model="form.id" placeholder="车辆编号" auto-complete="off" readonly="readonly"></el-input>
                    </el-form-item>
                    <el-form-item label="维修厂" :label-width="formLabelWidth" prop="maintainShopId">
                        <el-select v-model="form.maintainShopId" placeholder="请选择">
                            <el-option v-for="item in optionsMaintainShop" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="金额" :label-width="formLabelWidth" prop="amount">
                        <el-input v-model="form.amount" placeholder="金额" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
                        <el-input v-model="form.remark" placeholder="备注" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="maintainForm = false">取 消</el-button>
                    <el-button type="primary" @click="maintain(form)">确 定</el-button>
                </div>
            </el-dialog>
            <!--保险单记录 -->
            <el-dialog title="车辆维修管理" :visible.sync="insuranceForm">
                <el-form :model="form" :rules="rules" ref="form">
                    <el-form-item label="保单编号" :label-width="formLabelWidth" v-if="false">
                        <el-input v-model="form.insuranceId" placeholder="保单编号" auto-complete="off" readonly="readonly"></el-input>
                    </el-form-item>
                    <el-form-item label="车名" :label-width="formLabelWidth">
                        <el-input v-model="form.carname" placeholder="车名" auto-complete="off" readonly="readonly"></el-input>
                    </el-form-item>
                    <el-form-item label="车辆编号" :label-width="formLabelWidth">
                        <el-input v-model="form.id" placeholder="车辆编号" auto-complete="off" readonly="readonly"></el-input>
                    </el-form-item>
                    <el-form-item label="金额" :label-width="formLabelWidth" prop="insuredAmount">
                        <el-input v-model="form.insuredAmount" placeholder="金额" auto-complete="off" :readonly="form.insuranceId != 0"></el-input>
                    </el-form-item>
                    <el-form-item label="第三方责任险" :label-width="formLabelWidth" prop="thirdPartyLiability">
                        <el-input v-model="form.thirdPartyLiability" placeholder="如：车窗险，无则填无" auto-complete="off" :readonly="form.insuranceId != 0"></el-input>
                    </el-form-item>
                    <el-form-item label="乘客险" :label-width="formLabelWidth" prop="passengerLiability">
                        <el-input v-model="form.passengerLiability" placeholder="如：所有乘客" auto-complete="off" :readonly="form.insuranceId != 0"></el-input>
                    </el-form-item>
                    <el-form-item label="保费" :label-width="formLabelWidth" prop="premium">
                        <el-input v-model="form.premium" placeholder="保费" auto-complete="off" :readonly="form.insuranceId != 0"></el-input>
                    </el-form-item>
                    <el-form-item label="开始时间" :label-width="formLabelWidth" prop="startTime">
                        <el-date-picker v-model="form.startTime" placeholder="开始时间" type="datetime" default-time="12:00:00" auto-complete="off" :readonly="form.insuranceId != 0"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束时间" :label-width="formLabelWidth" prop="endTime">
                        <el-date-picker v-model="form.endTime" placeholder="开始时间" type="datetime" default-time="12:00:00" auto-complete="off" :readonly="form.insuranceId != 0"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="公司名称" :label-width="formLabelWidth" prop="companyName">
                        <el-input v-model="form.companyName" placeholder="公司名称" auto-complete="off" :readonly="form.insuranceId != 0"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="insuranceForm = false">取 消</el-button>
                    <el-button type="primary" @click="insurance(form)">{{ form.insuranceId | statubtnd() }}</el-button>
                </div>
            </el-dialog>
        </el-row>
        <!--分页插件-->
        <el-row>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,3,5,10,100, 200, 300, 400]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>
  </div>
</template>
<script>
export default {
    data() {
            let onlyone=(rule,value,callback)=>{
              if(!value){
                  return callback(new Error('请输入'))
              }else{
                  if(this.form.id==undefined){
                      this.form.id='';
                  }
                    this.$http.get("/api/cars/car/queryvin?vin="+value+"&id="+this.form.id).then((response)=>{
                            if(response.data!=0){
                                return callback(new Error('此号已经存在'))
                            }else{
                                    callback()
                            }
                        })
                    }
		    };
        return {
            url:this.$base_url+'/api/cars/upload/uploadImg?accessToken='+localStorage.getItem("token"),
            tableData:[],
            currentPage:1,//当前页面，默认1
            pageSize:5,//每页显示条数
            total:100,//分页总数量，默认值随便写，初始化时赋予新值
            carname:'',
            imageUrl: '',
            dialogFormVisible:false,
            maintainForm:false,
            insuranceForm:false,
            formLabelWidth: '120px',
            form:{},
            rules:{
                carname:[
                    {required:true,message:'请输入车辆名称',trigger:'blur'},
                    {min:3,max:7,message:'长度在3到7个字符',trigger:'blur'}
                ],
                type:[
                    {required:true,message:'请选择车辆类型',trigger:'change'}
                ],
                brandId:[
                    {required:true,message:'请选择车辆品牌',trigger:'change'}
                ],
                configId:[
                    {required:true,message:'请选择车辆配置',trigger:'change'}
                ],
                vin:[
                    {required:true,validator:onlyone,trigger:'blur'}
                ],
                buyPrice:[
                    {required:true,message:'请输入车辆进价',trigger:'blur'}
                ],
                price:[
                    {required:true,message:'请输入车辆租价',trigger:'blur'}
                ],
                state:[
                    {required:true,message:'请选择车辆状态',trigger:'change'}
                ],
                shopId:[
                    {required:true,message:'请选择门店',trigger:'change'}
                ],
                intro:[
                    {required:true,message:'请填写简介',trigger:'blur'}
                ],
                maintainShopId:[
                    {required:true,message:'请选择维修厂',trigger:'change'}
                ],
                amount:[
                    {required:true,message:'请输入维修金额',trigger:'blur'}
                ],
                remark:[
                    {required:true,message:'请输入维修信息备注',trigger:'blur'}
                ],
                insuredAmount:[
                    {required:true,message:'请输入保单金额',trigger:'blur'}
                ],
                thirdPartyLiability:[
                    {required:true,message:'请输入第三方责任险',trigger:'blur'}
                ],
                passengerLiability:[
                    {required:true,message:'请输入乘客险',trigger:'blur'}
                ],
                premium:[
                    {required:true,message:'请输入保险赔付金额',trigger:'blur'}
                ],
                startTime:[
                    {required:true,message:'请选择开始时间',trigger:'change'}
                ],
                endTime:[
                    {required:true,message:'请选择结束时间',trigger:'change'}
                ],
                companyName:[
                    {required:true,message:'请输入公司名称',trigger:'blur'}
                ]
            },
            optionsType: [],
            optionsBrand: [],
            optionsConfig: [],
            optionsState:[],
            optionsShop:[],
            optionsMaintainShop:[]
        };
      
    },
    created:function(){
        //初始化
        this.loadData();
        this.loadType();
        this.loadBrand();
        this.loadConfig();
        // this.loadState();
        this.loadShop();
        this.loadMaintainShop()
    },
    methods:{
        //图片上传成功后 
        handleAvatarSuccess(res, file) {
            alert("asdfadfa")
            alert(JSON.stringify(res));
        this.imageUrl = URL.createObjectURL(file.raw);
        // 往后台传的存到数据库中的
        this.form.coverImg=res.data;
      },
        //上传前图片类型和大小判断
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
        //加载数据
        loadData(){
            //动态菜单请求
            this.$http.post("/api/cars/car/queryAll?pageNo="+this.currentPage+"&pageSize="+this.pageSize,{
                carname:this.carname
                }).then((response) => {
                    if(response.data.code==2000){
                        console.log(response);
                        this.tableData = response.data.data.list;
                        this.total = response.data.data.total;
                    };
                
            });
                    
        },
        loadType() {
            this.$http.post('/api/cars/carType/queryAll?pageNo=1&pageSize=100000', {
            }).then((response) => {
                console.log(response);
                this.optionsType = response.data.data.list;
            });
        },
        loadBrand() {
            this.$http.post('/api/cars/brand/queryAll?pageNo=1&pageSize=100000', {
            }).then((response) => {
                console.log(response);
                this.optionsBrand = response.data.data.list;
            });
        },
        loadConfig() {
            this.$http.post('/api/cars/carTypeConfigDetails/queryAll?pageNo=1&pageSize=100000', {
            }).then((response) => {
                console.log(response);
                this.optionsConfig = response.data.data.list;
            });
        },
        // loadState() {
        //     this.$http.post('http://localhost:12130/api/cars/state/queryAll?pageNo=1&pageSize=100000', {
        //     }).then((response) => {
        //         console.log(response);
        //         this.optionsState = response.data.data.list;
        //     });
        // },
        loadShop() {
            this.$http.post('/api/cars/shop/queryAll?pageNo=1&pageSize=100000', {
            }).then((response) => {
                // alert(JSON.stringify(response));
                // alert(JSON.stringify(response.data.data));
                this.optionsShop = response.data.data.list;
            });
        },
        loadMaintainShop() {
            this.$http.post('/api/cars/maintainShop/queryAll?pageNo=1&pageSize=100000', {
            }).then((response) => {
                console.log(response);
                this.optionsMaintainShop = response.data.data.list;
            });
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize=val;
            this.loadData();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage=val;
            this.loadData();
        },
        search(){
            this.loadData();
        },
        //处理添加
        handleAdd(){
            //清空原来form
            this.form={};
            //更新显示名称
            this.title="车辆添加";
            //对话框显示
            this.dialogFormVisible=true;
            //重置表单
            // this.$refs.form.resetFields();
        },
        //处理编辑（弹出部门更新对话框）
        handleEdit(index, row) {
            console.log(index, row);
            this.form=JSON.parse(JSON.stringify(row));
            this.imageUrl=row.coverImg;
            // this.form=row;
            //更新显示名称
            this.title="车辆更新";
            //对话框显示
            this.dialogFormVisible=true;
        },
        //维修记录
        handleMaintain(index,row) {
            if(row.state == 1) {
                this.changeState(row);
            }else if(row.state == 2) {
                console.log(index, row);
                this.form=row;
                //更新显示名称
                this.title="车辆维修记录";
                //对话框显示
                this.maintainForm=true;
                //重置表单
                // this.$refs.form.resetFields();
            } 
        },

        //保险添加和查询
        handleInsurance(index,row) {
            if(row.insuranceId == 0) {
                console.log(index, row);
                this.form=row;
                //更新显示内容
                this.title="保险单记录表";
                //对话框显示
                this.insuranceForm=true;
                //重置表单
                // this.$refs.form.resetFields();
            }else {
                console.log(index, row);
                this.form=row;
                //更新显示内容
                this.title="保险单详情";
                //对话框显示
                this.insuranceForm=true;
            }
        },
        //提交表单数据（添加或者更新）
        saveInfo(){
            var _this = this;
            var  url ='/api/cars/car/update';
            if(this.form.id==''||this.form.id==null){
                url="/api/cars/car/insert"
            }
             this.$refs.form.validate((valid) =>{
                if(valid) {
                     _this=this;
                    //提交方法
                    this.$http.post(url, this.form)
                    .then(function (response) {
                        console.log(response);
                        //提交成功
                        if(response.data.code==2000){
                            //关闭弹出框
                            _this.dialogFormVisible=false;
                            //提示更新成功
                            _this.$message({
                                //  message: '恭喜你，这是一条成功消息',
                                message: response.data.message,
                                type: 'success'
                            });
                            //重新加载数据
                            _this.loadData();
                        }else {
                            _this.$message.error(response.data.message);
                        }
                    })
                    .catch(function (error) {
                        _this.$message.error('错了哦，这是一条错误消息');
                    });
                } else {
                    console.log('error submit!!');
                    this.loadData();
                    return false;
                }
             });
        },
        //改变车辆状态方法
        changeState(row){
            var _row = row;
            var _this = this;
            _row.state = 2;
            this.$http.post('/api/cars/car/update', _row).then((response) => {
                if(response.data.code==2000){
                    //提示更新成功
                    _this.$message({
                        //  message: '恭喜你，这是一条成功消息',
                        message: response.data.message,
                        type: 'success'
                    });
                    //重新加载数据
                    _this.loadData();
                }else {
                    _this.$message.error(response.data.message);
                }
            })
            .catch(function (error) {
                     _this.$message.error('错了哦，这是一条错误消息');
                });
        },
        //提交表单数据（维修记录）
        maintain(){
            var _this = this;
            var  url ='/api/cars/car/maintain';
            _this=this;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    //提交方法
                    this.$http.post(url, this.form)
                    .then(function (response) {
                        console.log(response);
                        //提交成功
                        if(response.data.code==2000){
                            //关闭弹出框
                            _this.maintainForm=false;
                            //提示更新成功
                            _this.$message({
                                //  message: '恭喜你，这是一条成功消息',
                                message: response.data.message,
                                type: 'success'
                            });
                            //重新加载数据
                            _this.loadData();
                        }else {
                            _this.$message.error(response.data.message);
                        }
                    })
                    .catch(function (error) {
                        _this.$message.error('错了哦，这是一条错误消息');
                    });
                } else {
                    console.log('error submit!!');
                    this.loadData();
                    return false;
                }
            })
        },
        //提交表单数据（保险记录）
        insurance(){
            var _this = this;
            var  url ='/api/cars/car/deleteInsurance';
            if(this.form.insuranceId== 0||this.form.id==null){
                url='/api/cars/car/carInsurance';
            }
            _this=this;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    //提交方法
                    this.$http.post(url, this.form)
                    .then(function (response) {
                        console.log(response);
                        //提交成功
                        if(response.data.code==2000){
                            //关闭弹出框
                            _this.insuranceForm=false;
                            //提示更新成功
                            _this.$message({
                                //  message: '恭喜你，这是一条成功消息',
                                message: response.data.message,
                                type: 'success'
                            });
                            //重新加载数据
                            _this.loadData();
                        }else {
                            _this.$message.error(response.data.message);
                        }
                    })
                    .catch(function (error) {
                        _this.$message.error('错了哦，这是一条错误消息');
                    });
                }  else {
                    console.log('error submit!!');
                    this.loadData();
                    return false;
                }
            })
        },
    },filters:{
        statusbtn: function(state){
            var _this = this;
            if(state==1){
                return '维修'
            }else if(state==2){
                return '返厂'
            }else {
                return '维修'
            }
        },
        statubtn: function(insuranceId) {
            var _this = this;
            if(insuranceId == 0) {
                return "入保"
            }else {
                return "保单详情"
            }
        },
        statubtnd:function(insuranceId) {
            var _this = this;
            if(insuranceId == 0) {
                return "确定"
            }else {
                return "取保"
            }
        }
    }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>